home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2380 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.9 KB  |  71 lines

  1. Path: crchh327.rich.bnr.ca!jhalpin
  2. From: jhalpin@bnr.ca (Joe Halpin)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: How do I prevent deleting of an object that is still being used?
  5. Date: 17 Jan 1996 13:39:41 GMT
  6. Organization: Bell-Northern Research, Richardson, TX
  7. Message-ID: <4diu6t$c5n@crchh327.rich.bnr.ca>
  8. References: <4dg9in$s5h@utopia.hacktic.nl>
  9. NNTP-Posting-Host: crchh518.rich.bnr.ca
  10.  
  11. In article <4dg9in$s5h@utopia.hacktic.nl>,
  12. Mike Tavares  <MIKET@cdynamics.com> wrote:
  13. >
  14. >I have some classes:
  15. >
  16. >class menuItem
  17. >    {
  18. >    ...
  19. >
  20. >    }
  21. >
  22. >
  23. >
  24. >class   menu
  25. >    {
  26. >
  27. >    list<menuItem>  theItems    // the items that are on this menu.
  28. >
  29. >    Register( menuItem  &anItem );
  30. >
  31. >    }
  32. >
  33. >
  34. >A menuItem can be on more than one menu.  When a menu is deleted it 
  35. >should delete all its menuItems UNLESS they are on another menu.  What is 
  36. >the typical way of setting this up.  I've heard of "contact" objects and 
  37. >"plug and socket" objects but I've never seen an implementation
  38. >pattern. any help is appreciated.
  39.  
  40. One possibility is to move the state of a menuItem into a separate
  41. class, and share that state among menuItem instances.
  42.  
  43. class menuItem;
  44.  
  45. class menuItemState {
  46.   friend menuItem;
  47.   int   refCount;
  48.   char *caption;
  49.   // whatever other member variables are used by menuItem
  50. };
  51.  
  52. class menuItem {
  53.   menuItemState *state;
  54.   ...
  55. };
  56.  
  57. The copy constructor and assignment operator for menuItem need to
  58. point menuItem::state at the state of the object being assigned, and
  59. increment the reference count. The destructor needs to decrement the
  60. count, and delete state when count gets to 0. This releives the menu
  61. from having to worry about it at all.
  62.  
  63. If I remember right, this is roughly the Flyweight pattern in "Design
  64. Patterns", by Gamma et al. You might also be able to use their Proxy
  65. pattern.
  66.  
  67. Joe
  68. -- 
  69. Joe Halpin        jhalpin@bnr.ca        BNR Richardson, TX       (214) 684-5657
  70. -------------------------------------------------------------------------------
  71.